const Base = require('./base.js');
const fs = require('fs');
const path = require('path');
const moment = require('moment');

module.exports = class extends Base {
    /**
     * 图片上传
     * @returns {any}
     */
    fileAction() {
        const files = this.file();
        let Path = null;
        if (files.file.size > 0) {
            let extName = '';  //后缀名
            switch (files.file.type) {
                case 'image/jpg':
                    extName = 'jpg';
                    break;
                case 'image/jpeg':
                    extName = 'jpg';
                    break;
                case 'image/png':
                    extName = 'png';
                    break;
                case 'image/x-png':
                    extName = 'png';
                    break;
                default:
                    extName = 'png';
                    break;
            }

            if (extName.length === 0) {
                return;
            }
            let avatarName = 'SY' + moment().format('X') + Math.random().toString().substr(2, 7) + '.' + extName;
            const filepath = 'd:/static/upload/' + avatarName;
            think.mkdir(path.dirname(filepath));
            // await rename(files.file.path, filepath);
            let readStream = fs.createReadStream(files.file.path);
            let writeStream = fs.createWriteStream(filepath);
            readStream.pipe(writeStream);
            Path = think.config('xcx.upload_domain') + 'upload/' + avatarName;
        }
        return this.success(Path);
    }
};
